package com.snapp.web.actions.access;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.snapp.util.object.model.ObjectModel;
import com.snapp.web.agents.AccessAgent;

/**
 * 
 * @author kile
 *
 */
public class Login extends CheckSession {
	
	public String execute(HttpServletRequest req) {
		
		AccessAgent aa = new AccessAgent();

		// attempt the login
		ObjectModel acc = aa.login(consolidateReadMap(req));
		
		if (acc == null) {
			setResults(RESULT_CODE_ERROR,"Invalid Credentials");
			
		} else {
			
			setResults(RESULT_CODE_SUCCESS,"Credentials found.");
			
			// get session
			HttpSession sess = req.getSession(true);
			sess.setAttribute("access", acc);

			// get permissions map
			@SuppressWarnings("unchecked")
			Map<String, String> pMap = (Map<String,String>)acc.getBean().getProperty("permits");
			
			// set permissions to session for validation
			sess.setAttribute("permits", pMap);

			try {
				setBodyElement(acc.getBean().toXML());
			} catch(Exception e) {
				log(e.getMessage(), e);
				setResults(RESULT_CODE_ERROR,"Unknown error parsing credentials");
			}
		}	
		
		String nxtPage = null;
		// execute session check
		if (getResultCode() == RESULT_CODE_ERROR) {
			nxtPage = super.bypass(req);
		} else {
			nxtPage = super.execute(req);
		}
		return nxtPage;
	}

}
